<template>
    <img id="background_index" :src=" user?.get_user()?.app_index_image || '../../public/background_index.jpg'" alt="">
    <div id="index_nav">
        <div style="display: inline-block; position: relative;">
            <div id="background_time">{{ time }}</div>
            <div id="myname"
                style="font-family: 'Helvetica Neue'; font-size: 20px; margin:0 0 0 10px;user-select: none;">
                {{ indextitle }}
                <span style="color:#17233d;">
                    幸运度:
                    <CountUp :end="count_user_g" :duration="4" :decimals="0" ref="count" v-font="20" />
                </span>
            </div>
        </div>
        <div id="_index_nav">
            <Menu style="background: rgba(0,0,0,0);" mode="horizontal" :theme="theme" active-name="1">
                <Submenu name="1" v-if="login_status">
                    <template #title>
                        <Icon type="ios-stats" />
                        我的空间
                    </template>
                    <MenuGroup title="基础">
                        <MenuItem name="1-1" @click="Click_goto('myself_admin')">空间</MenuItem>
                        <MenuItem name="1-2" @click="Click_goto('chat')">聊天</MenuItem>
                    </MenuGroup>
                    <MenuGroup title="状态">
                        <MenuItem name="1-4" @click="change_status(mystatus)">{{ mystatus }}</MenuItem>
                        <MenuItem name="1-5" @click="Click_logout">登出</MenuItem>
                    </MenuGroup>
                </Submenu>
                <MenuItem name="2" @click="Click_goto('life')">
                <Icon type="ios-paper" />
                生活
                </MenuItem>
                <MenuItem name="3" @click="Click_goto('aboutthis')">
                <Icon type="ios-help-circle" />
                关于
                </MenuItem>
                <Submenu name="4">
                    <template #title>
                        <Icon type="ios-stats" />
                        功能
                    </template>
                    <MenuGroup title="娱乐">
                        <MenuItem name="4-1" @click="Click_goto('music')">八音盒</MenuItem>
                        <MenuItem name="4-2" @click="Click_goto('video')">TV</MenuItem>
                        
                    </MenuGroup>
                    <MenuGroup title="关联">
                        <MenuItem name="4-4" @click="Click_goto('qianfan')">千帆</MenuItem>
                    </MenuGroup>
                </Submenu>
                <MenuItem name="5" @click="Click_goto('community')">
                <Icon type=" md-contacts" />社区
                </MenuItem>
                <br>
            </Menu>
        </div>


    </div>


    <div class="index_pre_info" ref="pre_info">
        <p></p>

    </div>
    <div v-if="page_card_d != undefined && page_card_d.length != 0">
        <div class="index_body">
            <Row>
                <Col span="6" v-for="(item, index) in page_card_d_current" :key="index">
                <Card class="backgroud_opcity card_body">
                    <template #title style="height: auto;">
                        <p style="color:#c5c8ce;font-size: 18px;">{{ item.title }}</p>
                    </template>
                    <div class="index_default" :id="item.life_data_id" @click="render_index_default">
                        {{ item.text }}
                    </div>
                </Card>
                </Col>

            </Row>

            <div
                style="position: absolute; left: 50%; margin-left: -71.79px; bottom: -50px; color:ghostwhite;opacity: 0.8; ">
                <Page :modelValue="1" :total=page_all_count :page-size=page_count simple
                    @on-change="render_body_page" />
            </div>
        </div>
    </div>
    <div v-else style="text-align: center;">
        <WELCOME/>
    </div>

    <div style="display: inline;">
        <GlobalFooter :links="links" :copyright="privating" />
    </div>
    <Login style="position:fixed;top:0px;left: 0px; width: 100vw; z-index: 100;"
       v-if="show_register" title="用户登录"
        @handleSubmit="handleSubmit" 
        :submit="'登录'"
         :fields="fields" 
         :buttons="buttons"
        @handleGotocommunity="handleGotocommunity" 
        @handleRegister_Retrieve =handleRegister_Retrieve />
    <Confirm :isVisible="show_confirm" @isconfirm="isconfirm" @iscancel="iscancel" :confirmText="'登录'"
        :cancelText="'社区'" :message="'请先登录! \n或移步到社区！'" />
</template>
<script setup>
import { useRouter, useRoute, } from "vue-router";
import { onMounted, ref, defineProps, nextTick, inject, onUnmounted,watch} from "vue"
import { get_default_data } from "../api/life";
import { check_token, login, logout,change_user_status } from "../api/user";
import Login from "../components/common/formdata.vue"
import Confirm from "../components/common/confirm.vue"
import { failure, success } from "@/static/js/alert";
import { websocket_start } from "@/static/js/socket/login";
import WELCOME from "@/components/common/interest/welcome.vue"

let login_status = ref(false)
const props = defineProps({
    global_button: {
        type: Boolean,
    }
});

let indextitle = ref("welcome")
let user = inject('user')()
let mystatus = ref(user.value?.get_user()?.status || '在线')
watch(() => user.value?.get_user()?.status, (newVal) => {
    // 处理初始加载空白问题
  mystatus.value = newVal
}, { immediate: true })
let show_confirm = ref(false)
let show_register = ref(false)
let count_user_g = ref(null)
let show_global_button = inject('global_button')
let theme = ref('light')
let Router = useRouter()
let Route = useRoute()
let time = ref()
let page_card_d_current = ref()
let page_card_d = ref([])
let pre_info = ref()
let page_count = 8
let page_all_count = ref()
let pre_info_d = ref("We cannot judge the value of a moment,untill it become a memory !")
const handleSubmit = async (form) => {
    const ua = form['username'];
    const ps = form['password']
    const judge = await login(ua, ps)
    if (judge.user) {
        user.value.set_user_info(judge.user)
        show_register.value = false
        login_status.value = false
        websocket_start(user.value.get_user().id);
        if (user.value.get_user_isfirstlogin()) { 
            websocket_start(user.value.get_user().id);
               user.value.set_user_isfirstlogin(false)
        }
        Router.go(0)
    }

};
const handleRegister_Retrieve = async (form) => { 
    if (show_global_button.value) {
        Router.push({ name: 'register_retrieve' ,});
    } else {
        const route = Router.resolve({ name: 'register_retrieve' });
        window.open(route.href, '_blank');
    }
}

const handleGotocommunity = async (form) => { 
        Click_goto('community')
}

const fields = [
    {
        id: 'username',
        label: '账号',
        type: 'text',
        placeholder: '请输入账号 (8-15个字符)',
        validation: {
            required: true,
            minLength: 8,
            maxLength: 15,
        },
    },
    {
        id: 'password',
        label: '密码',
        type: 'password',
        placeholder: '请输入密码 (至少6个字符，包含符号)',
        validation: {
            required: true,
            minLength: 6,
        },
    },
]
const buttons = [
    { text: '登录', action: 'handleSubmit' },
    { text: '注册/找回', action: 'handleRegister_Retrieve', requiresValidation: false },
    { text: '社区', action: 'handleGotocommunity', requiresValidation: false },
];

let links = [
    {
        key: '帮助',
        title: '帮助',
        href: '',
        blankTarget: true
    },
    {
        key: '',
        icon: '',
        href: '',
        blankTarget: true
    },
    {
        key: '条款',
        title: '条款',
        href: '',
        blankTarget: true
    }
]

let privating = 'henna © 2024 linyuansheng.com'
const render_index_default = async function (e) {
    const ID = e.target.getAttribute('id')
    Router.push({ name: 'render_life_Data' ,query:{id:ID}});
}


const render_body_page = function (index) { // body——card分页处理
    page_card_d_current.value = page_card_d.value.slice((index - 1) * page_count, index * page_count)
    if (page_card_d.value.length < index * page_count) {
    }
}

// 功能导航
const Click_goto = function (section) {
    if (show_global_button.value) {
        Router.push({ name: `${section}` });
    } else {
        const route = Router.resolve({ name: `${section}` });
        window.open(route.href, '_blank');
    }
}
const change_status = () => {
    try {
        mystatus.value = mystatus.value === "在线" ? "隐身" :
            mystatus.value === "隐身" ? "离线" : "在线";
        change_user_status(mystatus.value, user.value.get_user().id)
        user.value.set_user_info_by_key('status', mystatus.value)
    }
    catch (error) {
        console.log(error)
     }
   
}
// 退出账号
const Click_logout = async function  () {
    await logout()
    user.value.reset_userstore()
    user.value.set_user_info=undefined
    Router.go(0)
}


const datatime_ = function () { //主页时间展示
    time.value = new Date().toLocaleString();
}

const isconfirm = function () {
    show_confirm.value = false;
    show_register.value = true;
}

const iscancel = function () {
    show_confirm.value = true;
    Click_goto('community')
}

const getRandomInt = function (min, max) {
    // 修正：确保 min ≤ 随机数 < max
    return Math.floor(Math.random() * (max - min)) + min;
};

async function getOrUpdateLocalData(storageKey) {
    // 1. 尝试从本地存储读取数据
    const storedData = localStorage.getItem(storageKey);
    let data;

    if (storedData) {
        try {
            const parsedData = JSON.parse(storedData);
            if (parsedData.timestamp) {
                const storedDate = new Date(parsedData.timestamp);
                const today = new Date();
                const isSameDay =
                    storedDate.getFullYear() === today.getFullYear() &&
                    storedDate.getMonth() === today.getMonth() &&
                    storedDate.getDate() === today.getDate();

                if (isSameDay) {
    
                    data = parsedData.data;
                    return data;
                }
            }
        } catch (e) {
            console.error("解析本地存储数据失败", e);
        }
    }

    try {
        data = getRandomInt(0, 1000); 
 
        const dataToStore = {
            data: data,
            timestamp: new Date().toISOString(),
        };
        localStorage.setItem(storageKey, JSON.stringify(dataToStore));
        console.log("已生成并存储新数据:", data);
    } catch (error) {
        console.error("生成新数据失败", error);
        throw error; 
    }

    return data;
}


try { setInterval(datatime_, 100) }
catch { }

function render_info_index() {
    var last_ = 0;
    var lasting = 1;
    const pre_info_d_length = pre_info_d.value.length;
    const charDelay = 100; // 每个字符的显示间隔（毫秒）
    let lastTime = 0;

    function animateText(timestamp) {
        try {
            // 控制时间间隔
            if (timestamp - lastTime >= charDelay) {
                pre_info.value.childNodes[0].innerText += pre_info_d.value.substring(last_, lasting);
                last_ = lasting;
                lastTime = timestamp;

                if (pre_info_d_length === lasting) {
                    pre_info.value.childNodes[0].innerText = pre_info_d.value; // 保证最后一段文字完整显示
                    return;
                }

                lasting += 1;
            }
            requestAnimationFrame(animateText);
        } catch (error) {
            // 处理错误（如有需要）
        }
    }

    // 启动动画
    requestAnimationFrame(animateText);

    page_card_d_current.value = page_card_d.value.slice(0, page_count);
}


onMounted(async () => {

    // 加载完后渲染pre_info
    await nextTick()
    count_user_g.value=await getOrUpdateLocalData('count_user_g')
    const judge = await check_token()
    if (judge == 0) {
        failure("请求超时!")
        show_confirm.value = true
    } else if (judge == 401 || judge == 404) {
        failure("登录状态出错!")
        show_confirm.value = true
    } else {
        // 开启信息的同步
        user.value.initializeBroadcastChannel()
        login_status.value = true
        if (!user.value.get_user()) {
            user.value.set_user_info(judge.user);
        }
        show_confirm.value = false
        const id = user.value.get_user().id
        indextitle.value = user.value?.get_user()?.username
        // 获取初始数据，并对card进行分页处理
        const data = await get_default_data(id)
        if (data!=undefined&&data?.length >= 0) {
            page_card_d.value = data
        }
        
        // 如果是第一次登录，启动 WebSocket
        if (user.value.get_user_isfirstlogin()) { 
            websocket_start(user.value.get_user().id);
             user.value.set_user_isfirstlogin(false)
        }
    }
    datatime_()
    // 由于涉及dom操作但是还有有后续的dom操作。所以渲染pre有点问题。有待考究。
    if (page_card_d.value != undefined) {
        page_all_count.value = page_card_d.value.length
        render_info_index()
    } else {
        render_info_index()
    }
    // show_global_button.value = Number(localStorage.getItem("show_global_button"))

})
onUnmounted(() => { 
    user.value.cleanupUserStoreListener()
    
})  


</script>
<style scoped>
/* 字体包 */
@font-face {
    font-family: 'MyCustomFont';
    /* 自定义字体名字 */
    src: url('../fonts/breadshop-font/Breadshop-4nLED.otf') format("opentype");
    /* 指向字体文件的路径和格式 */
    font-weight: normal;
    /* 字体粗细 */
    font-style: normal;
    /* 字体样式 */
}


#background_index {
    min-width: 100%;
    min-height: 100%;
    position: fixed;
    left: 0;
    top: 0;
    z-index: -999;
    opacity: 0.99;
}


#background_time {
    position: absolute;
    left: 10px;
    font-size: 18px;
    bottom: -25px;
    user-select: none;
    width: 200px;

}


.backgroud_opcity {
    background: rgba(0, 0, 0, 0);
}

#index_theme {
    display: inline-block;
}

#index_nav {
    height: 65px;
}

#_index_nav {
    float: right;
}

.index_body {
    height: auto;
    position: relative;

}

.card_body {
    margin: 2px 20% 2px 20%;
    background-image: linear-gradient(to right, white, blue, violet);
    color: transparent;
    -webkit-background-clip: text;
    font-size: 15px;
}

.index_pre_info {
    height: 250px;
    text-align: center;
    font-size: 18px;

}

.index_pre_info>p {
    font-family: 'MyCustomFont';
    color: aqua;
    font-size: 28px;
}

#card_img_v {
    height: 50px;
    width: 50px;
    float: left;
}
.index_default {
    height: auto; /* 高度自适应 */
    min-height: 30px; /* 最小高度 */
    max-height: 150px; /* 最大高度 */
    width: 100%;
    overflow: hidden; /* 超出部分隐藏 */
    display: -webkit-box; /* 使用弹性盒子布局 */
    -webkit-box-orient: vertical; /* 垂直方向排列 */
    -webkit-line-clamp: 5; /* 限制显示的行数 */
    text-overflow: ellipsis; /* 超出部分显示省略号 */
    white-space: normal; /* 允许换行 */
}
</style>
